from rest_framework import serializers

from users.models import User


class UserSerializer(serializers.ModelSerializer):
    # 为分组提供数据
    class Meta:
        model = User
        fields = ['id', 'name', 'username', 'email', 'text', "password", 'avatar', 'birthday', 'sex', 'telephone']
        read_only_fields = ['id', 'username']
        extra_kwargs = {
            'password': {'write_only': True},
        }

    def create(self, validated_data):
        user = super().create(validated_data)
        password = validated_data.get('password')
        if password is not None:
            user.set_password(password)
            user.save()
        return user

    def update(self, instance, validated_data):
        super().update(instance, validated_data)
        password = validated_data.get('password')
        if password is not None:
            instance.set_password(password)
            instance.save()
        return instance
